﻿using System;
using System.Collections.Generic;
using System.Media;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using Flurl.Http;
using Newtonsoft.Json.Linq;
using WatsonWebserver;

namespace Voice
{
    public partial class Index : Form
    {
        //定义播放器
        private static readonly SoundPlayer AlertSoundPlayer = new SoundPlayer();

        //读取配置文件
        private static readonly JObject conf = Helper.GetConfig();

        public Index()
        {
            InitializeComponent();

            try
            {
                string ip = conf["localhost_ip"].ToString();
                int port = int.Parse(conf["port"].ToString());


                #region 开启服务

                Server server = new Server(ip, port, false, DefaultRoute);

                // add static routes
                server.Routes.Static.Add(HttpMethod.POST, "/alert", PostAlertRoute);
                
                server.Start();

                #endregion

                lab_ip.Text = ip;
                lab_port.Text = port.ToString();
                lab_tts.Text = conf["tts_server"].ToString();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                throw;
            }
        }

        /// <summary>
        ///     默认路由
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        private static async Task DefaultRoute(HttpContext ctx)
        {
            ctx.Response.StatusCode = 200;
            await ctx.Response.Send("Hi");
        }

        /// <summary>
        ///     Post路由
        /// </summary>
        /// <param name="ctx"></param>
        /// <returns></returns>
        private static async Task PostAlertRoute(HttpContext ctx)
        {
            string httpGetData;
            string ttsMessage;

            #region 获取客户端数据

            //获取json数据
            using (var jsonResponseStream = ctx.Request.Data)
            {
                try
                {
                    #region 读取客户端提交的数据

                    byte[] readBuffer = new byte[1000];
                    List<byte> allData = new List<byte>();
                    int readBytes;

                    do
                    {
                        readBytes = jsonResponseStream.Read(readBuffer, 0, readBuffer.Length);

                        for (var i = 0; i < readBytes; i++)
                        {
                            allData.Add(readBuffer[i]);
                        }
                    } while (readBytes > 0); //如果readBytes为0表示HttpWebResponse中的所有数据已经被读取完毕

                    httpGetData = Encoding.UTF8.GetString(allData.ToArray());

                    #endregion

                    #region Json数据处理

                    // JObject jObject = JObject.Parse(httpGetData);
                    // JToken jsonData = jObject;
                    // ttsMessage = Helper.GetJsonForKey(jsonData, "text");

                    #endregion


                    #region prometheusAlert数据处理

                    //var prometheusAlertResponseStreamString = ctx.Request.DataAsString;
                    var prometheusAlertResponseStreamString = httpGetData;
                    ttsMessage = Regex.Replace(prometheusAlertResponseStreamString, @"[\r\n]", "");

                    #endregion


                    #region 发送至TTS服务器

                    TTS(ttsMessage);

                    #endregion

                    ctx.Response.StatusCode = 200;
                    await ctx.Response.Send("Success!");
                }
                catch (Exception e)
                {
                    ctx.Response.StatusCode = 200;
                    ctx.Response.Send(e.Message);
                    throw;
                }
            }

            #endregion
        }


        /// <summary>
        ///     语音合成
        /// </summary>
        /// <returns></returns>
        private static async Task TTS(string text)
        {
            string ttsServer = conf["tts_server"].ToString();
            var result = await ttsServer
                .PostJsonAsync(new JObject
                {
                    {"text", text},
                    {"spk_id", 174}
                })
                .ReceiveJson<JObject>();

            if (Equals(Helper.GetJsonForKey(result, "code"), "200"))
            {
                Helper.PlayAlertSoud(AlertSoundPlayer, Helper.GetJsonForKey(result, "audio"));
            }
        }
    }
}